package com.flysky.controller.user;

import java.util.Date;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.flysky.common.MD5Util;
import com.flysky.common.ToolUtil;
import com.flysky.model.user.UserHbmModel;
import com.flysky.service.user.IUserService;

@Controller
public class UserActionController {

	Logger flyskyLogger = Logger.getLogger(UserActionController.class);
	@Autowired
	private IUserService userService = null;
	
	public void setUserService(IUserService userService) {
		this.userService = userService;
	}

	@RequestMapping(value="/register.htm")
	public ModelAndView registerUser(HttpServletRequest request,
			HttpServletResponse response,UserHbmModel user){
		ModelAndView mv = new ModelAndView("error");
		if(null == user){
			return mv;
		}
		//encrypt password using MD5
		user.setPassword(MD5Util.md5Hex(user.getPassword()));
		//set user create date
		user.setCreateDate(new Date());
		UserHbmModel newModel = this.userService.insertNewUser(user);
		this.flyskyLogger.info(newModel);
		mv.setViewName("homePage");
		return mv;
	}
	
	@RequestMapping(value="/loginCheck.htm")
	ModelAndView handleRequestInternal(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		flyskyLogger.info("some one is logining in system!");
		//get name and password from front form
		String name = request.getParameter("username");
		String password = request.getParameter("userPassWord");
		String frontUrl = request.getParameter("frontUrl");
		//build parameter 
		HashMap<String,String> param = new HashMap<String,String>();
		param.put("name", name);
		param.put("password", MD5Util.md5Hex(password));
		this.flyskyLogger.info(param);
		UserHbmModel userModel = this.userService.userLogin(param);
		this.flyskyLogger.info(userModel);
		ModelAndView result = new ModelAndView();
		HttpSession session = request.getSession();
		session.setAttribute("user", userModel);
		result.setViewName("homePage");
		if(null == userModel){
			result.setViewName("login");
		}
		if(!ToolUtil.isEmpty(frontUrl)){
			String content = request.getContextPath();
			frontUrl = frontUrl.replace(content, "");
			result.setViewName("redirect:"+frontUrl);
		}
		return result;
	}
	
	@RequestMapping(value="/logout.htm")
	public ModelAndView logoutAction(HttpServletRequest request,
			HttpServletResponse response){
		ModelAndView result = new ModelAndView("redirect:/");
		HttpSession session = request.getSession();
		session.removeAttribute("user");
		return result;
	}
}
